package com.xq.tmall.service;

import com.xq.tmall.agu.ferign.StockSectorSpider;
import com.xq.tmall.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class TaskQueueService {
    private static final String TASK_QUEUE_KEY = "eastmoney:page:tasks";
    private static final String PROCESSED_QUEUE_KEY = "eastmoney:page:processed";
    private static final String FAILED_QUEUE_KEY = "eastmoney:page:failed";

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    // 初始化任务队列
    public void initializeTasks(int totalPages) {
        // 清空旧数据
        redisTemplate.delete(TASK_QUEUE_KEY);
        redisTemplate.delete(PROCESSED_QUEUE_KEY);
        redisTemplate.delete(FAILED_QUEUE_KEY);

        // 添加所有页码任务
        for (int page = 1; page <= totalPages; page++) {
            redisTemplate.opsForList().rightPush(TASK_QUEUE_KEY, page);
        }
    }

    // 获取下一个任务
    public Integer getNextTask() {
        return (Integer) redisTemplate.opsForList().leftPop(TASK_QUEUE_KEY);
    }

    // 标记任务为已完成
    public void markTaskCompleted(Integer page) {
        redisTemplate.opsForList().rightPush(PROCESSED_QUEUE_KEY, page);
    }

    // 标记任务为失败
    public void markTaskFailed(Integer page) {
        redisTemplate.opsForList().rightPush(FAILED_QUEUE_KEY, page);
    }

    // 获取已完成任务数
    public long getCompletedCount() {
        return redisTemplate.opsForList().size(PROCESSED_QUEUE_KEY);
    }

    // 获取失败任务数
    public long getFailedCount() {
        return redisTemplate.opsForList().size(FAILED_QUEUE_KEY);
    }

    // 重试失败任务
    public void retryFailedTasks() {
        Long size = redisTemplate.opsForList().size(FAILED_QUEUE_KEY);
        for (long i = 0; i < size; i++) {
            Integer page = (Integer) redisTemplate.opsForList().leftPop(FAILED_QUEUE_KEY);
            if (page != null) {
                StockSectorSpider stockSectorSpider = SpringContextUtil.getBean(StockSectorSpider.class);
                boolean success = stockSectorSpider.processPageWithRetry(page);
                if (success) {
                } else {
                    this.markTaskFailed(page);
                }
                // 添加延迟以避免请求过于频繁
                try {
                    Thread.sleep(60000);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }
}
